<?php

Kurogo::includePackage('db');

class MapViewAPIModule extends APIModule 
{

    protected $id = 'mapview';
    protected $vmin = 1;
    protected $vmax = 1;    
    
    protected function initializeForCommand() 
	{
        
        switch($this->command)
		{
			case 'addmarker':
				
				break;
		
			case 'likes':
				$session = $this->getSession();
				if($this->isLoggedIn()) {
					$user = $session->getUser();
					$userID = $user->getUserID();
					//CHECK IF USER HAS ALREADY VOTED, IFSO: ON CLICK GET RID OF UPVOTE
					$postID = $this->getArg('id',0);
					$db = new db();
					$sql = "SELECT * FROM likes WHERE postID = '$postID' AND fbID = '$userID'";
					$result = $db->query($sql,array());
					$row = $result->fetch();
					if($row){
						$sql = "DELETE FROM likes WHERE postID = '$postID' AND fbID = '$userID'";
						$db->query($sql);
						$img = '/modules/posts/images/nolike.png';
					}
					else {
						$sql = "INSERT into likes (postID, fbID) VALUES ('$postID','$userID')";
						$db->query($sql);
						$img = '/modules/posts/images/like.png';
					}
					
					//COUNT LIKES
					$sql = "SELECT COUNT(*) as likes FROM likes WHERE postID = '$postID'";
					$result = $db->query($sql,array());
					$row = $result->fetch();
					
					$response = array('likes' => $row['likes'], 
									  'img' => $img);
					$this->setResponse($response);
					$this->setResponseVersion(1);
				}
				break;
			case 'flags':
				$session = $this->getSession();
				if($this->isLoggedIn()) {
					$user = $session->getUser();
					$userID = $user->getUserID();
					//CHECK IF USER HAS ALREADY VOTED, IFSO: ON CLICK GET RID OF UPVOTE
					$postID = $this->getArg('id',0);
					$db = new db();
					$sql = "SELECT * FROM flags WHERE postID = '$postID' AND fbID = '$userID'";
					$result = $db->query($sql,array());
					$row = $result->fetch();
					if($row){
						$sql = "DELETE FROM flags WHERE postID = '$postID' AND fbID = '$userID'";
						$db->query($sql);
						$img = '/modules/posts/images/noflag.png';
					}
					else {
						$sql = "INSERT into flags (postID, fbID) VALUES ('$postID','$userID')";
						$db->query($sql);
						$img = '/modules/posts/images/flag.png';
					}    
					$response = $img;
					$this->setResponse($response);
					$this->setResponseVersion(1);                    
				}
        }
    }
}